package lapsnake.model;

import java.beans.PropertyVetoException;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import lapsnake.model.data.Property;
import org.python.antlr.*;
import org.python.antlr.base.mod;
import org.python.antlr.runtime.ANTLRInputStream;
import org.python.antlr.runtime.CharStream;
import org.python.antlr.runtime.CommonTokenStream;
import org.python.antlr.runtime.RecognitionException;
import org.python.antlr.runtime.Token;

/**Constructs and holds a python abstract syntax tree.*/
public class PyAST {
	
	/**The name of the script to compile*/
	private String name;
	/**The script to compile*/
	public final Property<String> script;
	/**The module root.*/
	private LapModule root;
	
	
	public PyAST(String name, String script) {
		this.name = name;
		this.script = new Property<String>(script);
		compileAST();
	}
	
	public PyAST(String name)
	{
		this(name, "");
	}

	public String visualizeScriptNodes()
	{
		StringBuilder sb = new StringBuilder();
		root.visualizeScript(sb, 0);
		return sb.toString();
	}

	public void compileAST()
	{
		RecordingErrorHandler eh = new RecordingErrorHandler();
		
        CharStream input = null;
        try{input = new ANTLRInputStream(new ByteArrayInputStream(script.get().getBytes()));}
		catch (IOException e){System.err.println("NOPE.");}
        
        PythonLexer lexer = new PythonLexer(input);
        lexer.setErrorHandler(eh);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        PythonTokenSource indentedSource = new PythonTokenSource(tokens, name);
        tokens = new CommonTokenStream(indentedSource);
        PythonParser parser = new PythonParser(tokens);
        parser.setErrorHandler(eh);
        parser.setTreeAdaptor(new PythonTreeAdaptor());
        mod r = null;
        try
		{
			r = (mod) parser.file_input().getTree();
			
			//TODO present errors in a nicer way
			for(RecognitionException err : eh.errs)
	        {
	        	System.err.println("Error in parsing: "+err.toString());
				System.err.println("At line: "+err.line+", position "+err.charPositionInLine);
	        }
			
			
			try
			{
				root = new LapModule(this, r);
			}
			catch (PropertyVetoException e)
			{
				throw new RuntimeException("Internal error building the tree: ", e);
			}
		}
        catch (ClassCastException e)
        {
        	System.err.println("Error in parsing: "+e.getMessage());
        	Token errToken = parser.getTokenStream().get(parser.getTokenStream().index());
			System.err.println("At line: "+errToken.getLine()+", position "+errToken.getCharPositionInLine());
        }
		catch (RecognitionException e)
		{
			System.err.println("Error in parsing: "+e.getMessage());
			System.err.println("At line: "+e.line+", position "+e.charPositionInLine);
		}
	}
	public void uncompileAST()
	{
		StringBuilder sb = new StringBuilder();
		root.appendScript(sb, true, 0);
		script.set(sb.toString(), null, true);
	}
	
	
	
	@Override
	public String toString() {
		if(root == null)
			return "Uninitialized "+getClass().getSimpleName();
		StringBuilder sb = new StringBuilder();
		root.buildTreeString(sb, 0, true);
		return sb.toString();
	}
	
	public String getName() {
		return name;
	}

	public void subTreeChanged(LapNode subRoot)
	{
		uncompileAST();
	}
	public LapModule getRoot()
	{
		return root;
	}

	public String getScript()
	{
		return script.get();
	}
	/**Nodes may call this when building the tree to indicate that we have recovered from a problem with the AST.*/
	public void warning(String warning)
	{
		System.err.println(warning);
	}
}
